package org.lionel.thread.observer;

import java.util.Arrays;
import java.util.List;

/**
 * 模拟当前类使用多线程需要去处理一批id，并拿到结果 1. 创建处理方法并通过ObserverableRunnable去执行任务 2. 当ObserverableRunnable吧任务执行完成后提醒当前类做完了 3. 拿到返回值处理
 */
public class ThreadLifeCycleObserver implements LifeCycleListener {

    private Object LOCK = new Object();

    private void concurrentQuery(List<Integer> ids) {
        if (ids.size() == 0 && ids.isEmpty())
            return;

        ids.stream().forEach((id) -> {
            new Thread(new ObserverableRunnable(this) {
                @Override
                public void run() {
                    try {
                        notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                        System.out.printf("query for id = %s\n", id);
                        Thread.sleep(1000);
                        notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
                    } catch (InterruptedException e) {
                        notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));
                    }
                }
            }).start();
        });
    }

    /**
     * 这个方法可能是多个线程在回调所以需要使用同步锁
     * 
     * @param event
     */
    @Override
    public void onEvent(ObserverableRunnable.RunnableEvent event) {
        synchronized (LOCK) {
            System.out.println(event.getThread().getName() + " == " + event.getState());
        }
    }

    public static void main(String[] args) {
        ThreadLifeCycleObserver threadLifeCycleObserver = new ThreadLifeCycleObserver();
        threadLifeCycleObserver.concurrentQuery(Arrays.asList(1, 2, 3));
    }
}